package com.fpd.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.stereotype.Component;

/**
 * @desc 过滤器
 * @author wujiangbo
 * @date 2019年11月20日 下午4:12:01
 */
@Component
@ServletComponentScan
@WebFilter(urlPatterns = "/*", filterName = "LoginFilter")
public class LoginFilter implements Filter {

	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException {
		HttpServletResponse response = crossFilter(arg1);
		HttpServletRequest request = (HttpServletRequest) arg0;
		arg2.doFilter(request, response);
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {

	}

	/**
	 * @desc 解决跨域请求问题
	 * @author wujiangbo
	 * @date 2019年11月20日 下午4:12:13
	 * @param arg1
	 * @return
	 */
	private HttpServletResponse crossFilter(ServletResponse arg1) {
		HttpServletResponse response = (HttpServletResponse) arg1;

		// 指示的请求的响应是否可以暴露于该页面。当true值返回时它可以被暴露
		response.setHeader("Access-Control-Allow-Credentials", "true");

		// 响应标头指定 指定可以访问资源的URI路径
		response.setHeader("Access-Control-Allow-Origin", "*");

		// 响应标头指定响应访问所述资源到时允许的一种或多种方法
		response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");

		// 设置 缓存可以生存的最大秒数
		response.setHeader("Access-Control-Max-Age", "3600");

		//导出时设置，前端获取参数
		response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");

		// 设置 受支持请求标头
		response.setHeader("Access-Control-Allow-Headers", "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With,Authorization,Accept,User-Agent,Referer,Token,Area");
		return response;
	}

}
